﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KAsFrame.Common.Application;
using KAsFrame.Common.Dto;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace KAsFrame.Common.Controllers
{
    public abstract class CommonCurdController<TPrimaryKeyType, T, TCreateDto, TUpdateDto, TDto> : ControllerBase
        where T : IEntity<TPrimaryKeyType>, new()
        where TCreateDto : IEntityDto<TPrimaryKeyType>, new()
        where TUpdateDto : IEntityDto<TPrimaryKeyType>, new()
        where TDto : IEntityDto<TPrimaryKeyType>, new()
    {
        protected readonly ICommonCurdAppService<TPrimaryKeyType, T, TCreateDto, TUpdateDto, TDto> _appService;

        public CommonCurdController(ICommonCurdAppService<TPrimaryKeyType, T, TCreateDto, TUpdateDto, TDto> appService)
        {
            _appService = appService;
        }

        [HttpPost]
        public async Task<ApiResult<string>> CreateAsync(TCreateDto createDto)
        {
            // 防止long返回异常
            var result = ApiResult<string>.IsSuccess();
            result.Data = (await _appService.CreateAsync(createDto)).ToString();
            return result;
        }

        [HttpPut]
        public async Task<ApiResult<bool>> UpdateAsync(TUpdateDto updateDto)
        {
            var result = ApiResult<bool>.IsSuccess();
            result.Data = await _appService.UpdateAsync(updateDto);
            return result;
        }

        [HttpDelete]
        public async Task<ApiResult<bool>> DeleteAsync(TPrimaryKeyType id)
        {
            var result = ApiResult<bool>.IsSuccess();
            result.Data = await _appService.DeleteAsync(id);
            return result;
        }

        [HttpGet]
        public async Task<ApiResult<TDto>> GetAsync(TPrimaryKeyType id)
        {
            var result = ApiResult<TDto>.IsSuccess();
            result.Data = await _appService.GetAsync(id);
            return result;
        }

        [HttpPost]
        public async Task<ApiResult<PageReturnDto<TDto>>> GetPageListAsync(PageReqDto pageReqDto)
        {
            var result = ApiResult<PageReturnDto<TDto>>.IsSuccess();
            result.Data = await _appService.GetPageListAsync(pageReqDto);
            return result;
        }
    }
}
